// pages/goods-detail/goods-detail.js
Page({
    data: {
        goods: null,
        id: null
    },

    onLoad(options) {
        if (options.id) {
            this.setData({ id: options.id });
            this.fetchGoodsDetail(options.id);
        }
    },
    
    // 获取商品详情
    async fetchGoodsDetail(id) {
        console.log('开始获取商品详情，商品ID:', id);
        try {
            console.log('准备发送网络请求...');
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `http://localhost:3000/api/test/goods/${id}`,
                    method: 'GET',
                    success: (response) => resolve(response),
                    fail: (error) => reject(error)
                });
            });

            if (res.statusCode === 200) {
                let goodsData;
                if (res.data.data) {
                    goodsData = res.data.data;
                } else if (res.data) {
                    goodsData = res.data;
                } else {
                    throw new Error('无法解析商品数据');
                }
                
                if (!goodsData.id || !goodsData.name || !goodsData.price) {
                    throw new Error('商品数据不完整');
                }

                const formattedGoods = {
                    id: goodsData.id,
                    name: goodsData.name,
                    price: goodsData.price,
                    image: goodsData.image,
                    description: goodsData.description || '暂无描述',
                    category_id: goodsData.category_id
                };
                
                this.setData({ goods: formattedGoods });
                console.log('商品数据设置完成:', this.data.goods);
            } else {
                throw new Error(`请求失败，状态码: ${res.statusCode}`);
            }
        } catch (error) {
            console.error('获取商品详情失败，错误详情:', error);
            wx.showToast({
                title: error.message || '获取商品详情失败',
                icon: 'none',
                duration: 2000
            });
        }
    },

    // 加入购物车
    addToCart() {
        if (!this.data.goods) return;
    
        try {
            // 获取当前购物车数据
            const cartItems = wx.getStorageSync('cartItems') || [];
            const selectedDishes = wx.getStorageSync('selectedDishes') || {};
    
            // 更新商品数量
            const currentQuantity = selectedDishes[this.data.goods.id] || 0;
            selectedDishes[this.data.goods.id] = currentQuantity + 1;
    
            // 更新购物车列表
            const existingItemIndex = cartItems.findIndex(item => item.id === this.data.goods.id);
            if (existingItemIndex > -1) {
                cartItems[existingItemIndex].quantity = selectedDishes[this.data.goods.id];
            } else {
                cartItems.push({
                    ...this.data.goods,
                    quantity: 1
                });
            }
    
            // 保存更新后的数据到本地存储
            wx.setStorageSync('cartItems', cartItems);
            wx.setStorageSync('selectedDishes', selectedDishes);
    
            // 更新所有相关页面的数据
            const pages = getCurrentPages();
            
            // 更新菜单页面的数据
            const menuPage = pages.find(page => page.route === 'pages/menu/menu');
            if (menuPage) {
                // 更新菜品列表中的数量
                const updatedDishes = menuPage.data.dishes.map(dish => ({
                    ...dish,
                    quantity: selectedDishes[dish.id] || 0
                }));
    
                // 根据当前分类和搜索关键词筛选菜品
                const filteredDishes = updatedDishes.filter(dish => 
                    (menuPage.data.currentCategory === 1 || dish.category_id === menuPage.data.currentCategory) &&
                    (!menuPage.data.searchKeyword || 
                    dish.name.toLowerCase().includes(menuPage.data.searchKeyword.toLowerCase()))
                );
    
                menuPage.setData({
                    selectedDishes,
                    dishes: updatedDishes,
                    filteredDishes,
                    cartCount: Object.values(selectedDishes).reduce((sum, quantity) => sum + quantity, 0)
                });
            }
    
            // 更新购物车页面的数据
            const cartPage = pages.find(page => page.route === 'pages/cart/cart');
            if (cartPage) {
                cartPage.setData({
                    cartItems: cartItems,
                    totalPrice: cartItems.reduce((total, item) => total + item.price * item.quantity, 0)
                });
            }
    
            wx.showToast({
                title: '已加入购物车',
                icon: 'success'
            });
        } catch (error) {
            console.error('添加到购物车失败:', error);
            wx.showToast({
                title: '添加失败，请重试',
                icon: 'none'
            });
        }
    },

    // 立即购买
    buyNow() {
        if (!this.data.goods) return;

        const orderItems = [{
            ...this.data.goods,
            quantity: 1
        }];

        wx.setStorageSync('orderItems', orderItems);
        wx.navigateTo({
            url: '/pages/order/order'
        });
    }
});